<template>
    <Form :label-width="100" :model="formValidate" ref="formValidate" :rules="ruleValidate">
        <div v-for="(item, index) in formValidate.flagList" :key="index">
            <p>第{{ index + 1 }}个flag:</p>
            <FormItem
                label="Flag："
                :prop="'flagList.' + index + '.flag'"
                :rules="[{ required: item.edit, message: '不能为空', trigger: 'change' },{
                    validator: (rule, value, callback) => {
                        let copyAnswers = JSON.parse(
                            JSON.stringify(formValidate.flagList)
                        );
                        copyAnswers.splice(index, 1);
                        if (
                            item.flag &&
                            copyAnswers
                                .map((answer) => answer.flag)
                                .includes(item.flag)
                        ) {
                            callback('Flag内容不能相同');
                        } else {
                            callback();
                        }
                    }
                }]"
            >
                <Input
                    type="textarea"
                    :maxlength="200"
                    v-model.trim="item.flag"
                    placeholder="请输入提示内容" :disabled='step==="mid"'
                ></Input>
                <!-- <span v-if="!item.edit" style="word-break:break-all;margin-top:10px;">{{
                    item.flag
                }}</span> -->
            </FormItem>
            <FormItem
                v-if="showScore != false"
                label="分值："
                :prop="'flagList.' + index + '.score'"
                :rules="[{ required: item.edit, message: '不能为空', trigger: 'change' }]"
            >
                <Input
                    type="textarea"
                    :maxlength="200"
                    v-model.trim="item.score"
                    placeholder="请输入分值" :disabled='step==="mid"'
                ></Input>
                <!-- <span v-if="!item.edit" style="word-break:break-all;margin-top:10px;">{{
                    item.score
                }}</span> -->
            </FormItem>
            <Divider dashed style="margin-top:0px;" />
        </div>
    </Form>
</template>
<script>
import {
    createCtfTargetTags,
    modifyCtfTargetTags,
    delCtfTargetTags,
    queryCtfTargetTags,
    clearCtfTargetTags,
    changeTagVisible
} from '@/api/drill_compete';
import { getQuestionSolveStatic } from '@/api/compitionStatic';
import { format } from '@/libs/utils';
export default {
    props: ['target', 'showScore','step'],
    data() {
        const validateScore = (rule, value, callback) => { //验证只能填入数字
					var reg = new RegExp("^(?!0)(?:[0-9]{1,3}|1000)$");
					//验证警戒值
					if(value || value === 0) {
						if(!reg.test(value)) {
							callback(new Error('请输入1-1000的整数'));
						} else {
							callback()
						}
					} else {
						callback()
					}
				}
        return {
            showModal: false,
            currentItem: null,
            index: 0,
            flagList: [],
            totalCount: 0,
            tag: {},
            tagModal: {
                show: false,
                loading: true,
                title: '添加Tag'
            },
            tagInfo: { flagList: [] },
            formValidate: {
                //					chaId: this.chaId,
                //					tag: "",
                flagList: []
            },
            ruleValidate: {
                flag: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],
                score: [{
                    required: true,
                    type: 'number',
                    message: '分值不能为空',
                    trigger: 'blur'
                }, {
                    validator: validateScore,
                    trigger: 'blur'
                }],
            },
            tagCol: [
                {
                    title: '名称',
                    key: 'info',
                    //						align: 'left',
                    ellipsis: true,
                    tooltip: true,
                    render: (h, params) => {
                        if (params.row.edit) {
                            return h('Input', {
                                props: {
                                    value: params.row.value,
                                    type: 'textarea',
                                    maxlength: 200,
                                    autosize: '{minRows: 2,maxRows: 5}'
                                }
                            });
                        } else {
                            return h('span', params.row.tag);
                        }
                    }
                },
                //					{
                //						title: 'createTime',
                //						key: 'createTime',
                //						align: 'left',
                //						ellipsis: true,
                //						tooltip:true
                //					},
                {
                    title: '操作',
                    width: 140,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            //											this.tagModal.show = true;
                                            //											this.tagModal.title = '修改tag';
                                            //											this.getCtfTargetTagsInfo(params.row);
                                            //											params.row.edit = true;
                                            this.saveCtfTargetTags(params.row);
                                        }
                                    }
                                },
                                '确定'
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            //											this.tagModal.show = true;
                                            //											this.tagModal.title = '修改tag';
                                            //											this.getCtfTargetTagsInfo(params.row);
                                            params.row.edit = true;
                                        }
                                    }
                                },
                                '修改'
                            ),
                            h(
                                'Poptip',
                                {
                                    props: {
                                        confirm: true,
                                        'ok-text': '确定',
                                        'cancel-text': '取消',
                                        type: 'error',
                                        size: 'large',
                                        title: '你确定要删除吗?',
                                        transfer: true
                                    },
                                    style: {
                                        marginLeft: '0px'
                                    },
                                    on: {
                                        'on-ok': () => {
                                            this.delCtfTargetTags(params.row.tagId);
                                        }
                                    }
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type: 'error',
                                                size: 'small'
                                            },
                                            style: {
                                                marginRight: '5px'
                                            }
                                        },
                                        '删除'
                                    )
                                ]
                            )
                        ]);
                    }
                }
            ],
            timeOptions: {},
            startDate: new Date()
        };
    },
    computed: {},
    filters: {},
    watch: {},
    mounted() {
        this.formValidate.flagList = JSON.parse(
            JSON.stringify(this.target.targetFlags || this.target.drTargetTeamFlags || [])
        );
    },
    created() {},
    methods: {
        addTag() {
            this.index++;
            this.flagList.push({
                info: '',
                index: this.index,
                infoVisibility: 0,
                questionId: this.target.questionId,
                sceneId: this.$route.query.id,
                targetId: this.target.id,
                //					promptTime:this.startDate,
                promptTime: this.startDate,
                time: this.startDate,
                timer: false,
                type: 0,
                edit: true
            });
        },
        removeTag(index) {
            this.flagList.splice(
                this.flagList.findIndex((tag) => tag.index === index),
                1
            );
        },
        queryCtfTargetTags() {
            let params = {
                sceneId: this.$route.query.id,
                questionId: this.target.questionId,
                targetId: this.target.id,
                pageIndex: 1,
                pageSize: 10000
            };
            queryCtfTargetTags(params).then((data) => {
                if (data.code == 1) {
                    this.flagList = data.data.items || data.data;
                    this.formValidate.flagList = data.data.items || data.data;
                    this.flagList.forEach((tag) => {
                        this.$set(tag, 'edit', false);
                        if (tag.promptTime) {
                            this.$set(tag, 'timer', true);
                            this.$set(tag, 'time', tag.promptTime);
                        }
                    });
                    if (data.data.items) {
                        this.index = data.data.items.length;
                    }
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        delCtfTargetTags(id) {
            delCtfTargetTags(id).then((data) => {
                if (data.code == 1) {
                    this.$Message.info(data.message);
                    this.queryCtfTargetTags();
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        modifyCtfTargetTags() {
            if (this.tag.info == '') {
                this.$Message.warning('提示内容不能为空');
                return;
            }
            if (this.tag.timer == false) {
                this.tag.promptTime = '';
            }
            modifyCtfTargetTags(this.tag).then((data) => {
                //					this.cancelLoading('tagModal');
                if (data.code == 1) {
                    this.$Message.info(data.message);
                    //						this.tagModal.show = false;
                    //						let boardCast = {
                    //							chaId:this.chaId,
                    //							op:"修改",
                    //							type:"提示",
                    //							name:this.tag.tag
                    //						}
                    //						this.$emit('addBoardCast', boardCast)
                    this.queryCtfTargetTags();
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        createCtfTargetTags() {
            if (this.tag.info == '') {
                this.$Message.warning('提示内容不能为空');
                return;
            }
            if (this.tag.timer == false) {
                this.tag.promptTime = '';
            }
            createCtfTargetTags(this.tag).then((data) => {
                //					this.cancelLoading('tagModal');
                if (data.code == 1) {
                    this.$Message.info(data.message);
                    //						this.tagModal.show = false;
                    this.queryCtfTargetTags();
                    //						let boardCast = {
                    //							chaId:this.chaId,
                    //							op:"添加",
                    //							type:"提示",
                    //							name:this.tag.tag
                    //						}
                    //						this.$emit('addBoardCast', boardCast)
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 判断传入的时间字符串是否在当前时间之前
        isBeforeTimestamp(dataStr) {
            return new Date(dataStr) <= new Date();
        },
        saveCtfTargetTags(tag, noValidation) {
            if (this.isBeforeTimestamp(tag.promptTime) && !noValidation) {
                // 隐藏、展示操作不需要验证时间
                this.$Message.warning('显示时间不得早于当前时间');
                return;
            }
            this.tag = tag;
            //				this.$refs['formValidate'].validate((valid) => {
            //          		if (valid) {
            if (!tag.id) {
                this.createCtfTargetTags();
            } else {
                this.modifyCtfTargetTags();
            }
            //          		}else{
            //          			this.cancelLoading('ctfModal');
            //          		}
            //          	})
        },
        getCtfTargetTagsInfo(data) {
            this.formValidate = JSON.parse(JSON.stringify(data));
        },
        changePage(page) {
            this.queryCtfInfo.page = page;
            this.queryCtfList();
        },
        changeSize(size) {
            this.queryCtfInfo.rows = size;
            this.queryCtfList();
        },
        cancelLoading(name) {
            this[name].loading = false;
            setTimeout(() => {
                this[name].loading = true;
            });
        },
        cancel(name) {
            this.$refs[name].resetFields();
        },
        changeTagVisible(item) {
            let params = JSON.parse(JSON.stringify(item));
            params.infoVisibility = params.infoVisibility == 0 ? 1 : 0;
            this.saveCtfTargetTags(params, true);
            //		  		changeTagVisible(item.id,status).then(data => {
            //		  			if(data.code == 1){
            //		  				this.queryCtfTargetTags();
            //		  			}else{
            //		  				this.$Message.warning(data.message);
            //		  			}
            //		  		})
        },
        // 查询题目解决情况
        checkQuestionSolve(item) {
            getQuestionSolveStatic({
                pageIndex: 1,
                pageSize: 10,
                sceneId: this.$route.query.id,
                questionId: item.questionId,
                finishStatus: 1
            })
                .then(({ code, data, message }) => {
                    if (code === 1) {
                        if (data.total) {
                            // 有团队已经解答出题目，需要给出提示
                            this.currentItem = item;
                            this.showModal = true;
                        } else {
                            this.changeTagVisible(item);
                        }
                    } else {
                        this.$Message.warning(message);
                    }
                })
                .catch(() => {
                    this.$Message.error('获取题目解答详情异常');
                });
        },
        changeTime(time, item) {
            if (this.isBeforeTimestamp(time)) {
                this.$Message.warning('显示时间不得早于当前时间');
            }
            item.promptTime = time + ':00';
        },
        // 默认十分钟后放出提示
        setTime(item) {
            let timeStr = format(new Date(new Date().getTime() + 600000));
            item.time = timeStr;
            item.promptTime = timeStr;
        }
    }
};
</script>

<style scoped>
.btn-group {
    height: 32px;
    display: flex;
    align-items: center;
}
.btn-group > button {
    margin-right: 6px;
}
.btn-group > button:last-child {
    margin-right: 0;
}
</style>
